import base64
import datetime
from flask import Blueprint, make_response, jsonify, request, g
from flask_restful import Resource

import time
from PIL import Image
from io import BytesIO
from math import isclose

import math

from apps.dbConnect.dbCurd import dbCurdD
from apps.dbConnect.dbTransaction import dbTransactionCurd
from apps.ext import db
from apps.model.dbTable import fmesApiModel

from comm.constant import CONST
from setting import login_required


project = Blueprint('basic', __name__)



# 进货送检过滤查询
class mfTiTiView(Resource):
    # 查询表头
    # @login_required
    def get(self):
        """
        查询送检单表头数据
        :return:
        """
        args = request.args
        # print(args)
        ti_no = args.get('ti_no',None)
        # 0常规检/1复检
        type = args.get('type',None)
        str_date = args.get('str_date',None)
        est_date = args.get('est_date',None)
        print(ti_no)
        pmrStr = ''
        pmr = {}
        if ti_no !=None and ti_no!='':
            pmrStr += 'and a.ti_no like :ti_no'
            pmr['ti_no'] = '%' + ti_no + '%'
        if type=='1':
            pmrStr +=' and b.QTY_RCK>0'
        if type=='0':
            pmrStr +=' and B.D_QTY>0'
        if str_date !=None and str_date!='':
            pmrStr += ' and a.ti_dd>=:str_date'
        if est_date !=None and est_date!='':
            pmrStr += ' and a.ti_dd<=:est_date'


        pmr['str_date'] = str_date
        pmr['est_date'] = est_date
        sql1 = """
select A.BIL_TYPE,A.DEP, B.QTY_RCK,A.TI_NO,FORMAT(A.TI_DD , 'yyyy-MM-dd') AS TI_DD,C.CUS_NO,C.NAME AS CUS_NAME,0 AS [select] from MF_TI A
LEFT JOIN (SELECT SUM(ISNULL(QTY_RCK,0)) AS QTY_RCK,SUM(ISNULL(QTY,0)-ISNULL(QTY_RTN,0)) AS D_QTY,TI_NO,TI_ID FROM TF_TI GROUP BY TI_NO,TI_ID) B ON A.TI_NO=B.TI_NO AND A.TI_ID=B.TI_ID
LEFT JOIN CUST C ON A.CUS_NO=C.CUS_NO
where isnull(A.CLOSE_ID,'')!='T' and isnull(A.CHKTY_ID,'')='T' AND isnull(A.SCAN_USR,'')!='' AND B.TI_ID='TI' {0}
        """.format(pmrStr)

        # sql1 = """
        # select top 50 B.QTY_RCK,A.TI_NO,FORMAT(A.TI_DD , 'yyyy-MM-dd') AS TI_DD,C.CUS_NO,C.NAME AS CUS_NAME,0 AS [select] from MF_TI A
        # LEFT JOIN (SELECT SUM(ISNULL(QTY_RCK,0)) AS QTY_RCK,SUM(ISNULL(QTY,0)-ISNULL(QTY_RTN,0)) AS D_QTY,TI_NO,TI_ID FROM TF_TI GROUP BY TI_NO,TI_ID) B ON A.TI_NO=B.TI_NO AND A.TI_ID=B.TI_ID
        # LEFT JOIN CUST C ON A.CUS_NO=C.CUS_NO
        #
        #         """
        print(sql1)
        data,err = dbCurdD.dbListJon(sql1,pmr)
        if err!=None :
            return make_response(jsonify({'msg':'查询失败:'+err }), 202)
        # print(data)
        # dataList = [
        #     {"ti_no":"TI20230609001","cus_no":"a0001","cus_name":"广州天心软件科技有限公司","ti_dd":"2023-06-09","select":False},
        #     {"ti_no":"TI20230609002","cus_no":"a0002","cus_name":"深圳天心软件科技有限公司aaaadasdsadasdarewasfsfsdf","ti_dd":"2023-06-10","select":False}
        # ]
        result = {}
        result['data'] = data
        msg = {'msg':'成功',"result":result}
        return make_response(jsonify(msg), 200)

    # 查询表身
    def post(self):
        """
        查询送检单表身数据
        :return:
        """
        data = request.get_json()
        # print(data)
        # time.sleep(1)
        # 0常规检验
        # 1复检
        type_ = data.get('type',0)

        ti_no = data.get('data',None)
        # print(ti_no)
        # print(type(ti_no))
        if ti_no is None or ti_no=='':
            return make_response(jsonify({'msg': '单据单号不能为空'}), 202)

        # print(ti_no)
        if type(ti_no)!=list:
            return make_response(jsonify({'msg': '单据单号参数类型不对'}), 202)
        if len(ti_no) == 0:
            return make_response(jsonify({'msg': '请选择过滤单号'}), 202)
        if len(ti_no) == 1:
            tilistStr = "a.ti_no='{0}'".format(ti_no[0])
        else:
            tilistStr = "a.ti_no in {0}".format(str(tuple(ti_no)))
        if type_==0:
            print('常规检')
            sql1_ = """
select b.cas_no,b.free_id,b.sh_no_cus,b.cus_os_no,b.bat_no,b.rem, b.bil_no,b.est_itm,b.itm,b.prd_mark,a.dep,a.cus_no,b.wh,b.PRD_MARK,a.BIL_TYPE,a.ti_no+'/'+cast(b.itm as varchar(20)) as id,'' as code,a.ti_no,FORMAT(a.ti_dd , 'yyyy-MM-dd') as ti_dd,0 as qty_ok,0 as qty_lost,'' as spc_no,'' as spc_name,'' as prc_id,'' as prc_name, isnull(b.qty_rtn,0) as qty_rtn,isnull(b.qty,0)-isnull(b.qty_rtn,0) as d_qty,isnull(b.qty,0) as qty,b.prd_no,c.name as prd_name from MF_TI A
LEFT JOIN TF_TI B ON A.TI_NO=B.TI_NO AND A.TI_ID=B.TI_ID
left join prdt c on b.prd_no=c.prd_no
where isnull(A.CLOSE_ID,'')!='T' and isnull(A.CHKTY_ID,'')='T' AND isnull(A.SCAN_USR,'')!='' and isnull(b.qty,0)-isnull(b.qty_rtn,0)>0 AND B.TI_ID='TI' and {0}
            """.format(tilistStr)
            # sql1_ = """
            # select top 1000 a.ti_no+'/'+cast(b.itm as varchar(20)) as id,'' as code,a.ti_no,FORMAT(a.ti_dd , 'yyyy-MM-dd') as ti_dd,0 as qty_ok,0 as qty_lost,'' as spc_no,'' as spc_name,'' as prc_id,'' as prc_name, isnull(b.qty_rtn,0) as qty_rtn,isnull(b.qty,0)-isnull(b.qty_rtn,0) as d_qty,isnull(b.qty,0) as qty,b.prd_no,c.name as prd_name from MF_TI A
            # LEFT JOIN TF_TI B ON A.TI_NO=B.TI_NO AND A.TI_ID=B.TI_ID
            # left join prdt c on b.prd_no=c.prd_no
            #             """
            # sql1_ = """
            # select top 50 a.ti_no+'/'+cast(b.itm as varchar(20)) as id,'' as code,a.ti_no,FORMAT(a.ti_dd , 'yyyy-MM-dd') as ti_dd,0 as qty_ok,0 as qty_lost,'' as spc_no,'' as spc_name,'' as prc_id,'' as prc_name, isnull(b.qty_rtn,0) as qty_rtn,isnull(b.qty,0)-isnull(b.qty_rtn,0) as d_qty,isnull(b.qty,0) as qty,b.prd_no,c.name as prd_name from MF_TI A
            # LEFT JOIN TF_TI B ON A.TI_NO=B.TI_NO AND A.TI_ID=B.TI_ID
            # left join prdt c on b.prd_no=c.prd_no
            #             """
        else:
            print('复检')
            sql1_ = """
select b.cas_no,b.free_id,b.sh_no_cus,b.cus_os_no,b.bat_no,b.rem,b.bil_no,b.est_itm,b.itm,b.prd_mark,a.dep,a.cus_no,b.wh,b.PRD_MARK,a.BIL_TYPE,a.ti_no+'/'+cast(b.itm as varchar(20)) as id,'' as code, a.ti_no,FORMAT(a.ti_dd , 'yyyy-MM-dd') as ti_dd,0 as qty_ok,0 as qty_lost,'' as spc_no,'' as spc_name,'' as prc_id,'' as prc_name, isnull(b.qty_rtn,0) as qty_rtn,isnull(b.QTY_RCK,0) as d_qty,isnull(b.qty,0) as qty,b.prd_no,c.name as prd_name from MF_TI A
LEFT JOIN TF_TI B ON A.TI_NO=B.TI_NO AND A.TI_ID=B.TI_ID
left join prdt c on b.prd_no=c.prd_no
where isnull(A.CLOSE_ID,'')!='T' and isnull(A.CHKTY_ID,'')='T' AND isnull(A.SCAN_USR,'')!=''  AND B.TI_ID='TI' and isnull(QTY_RCK,0)>0 and {0}
            """.format(tilistStr)
        print(sql1_)
        result,err = dbCurdD.dbListJon(sql1_,{})
        if err!=None:
            return make_response(jsonify({'msg': '查询失败:' + err}), 202)
        if len(result)==0:
            return make_response(jsonify({'msg': '没有查询到数据:'}), 202)
        for itm in result:
            # 默认不展开
            itm['unfold'] = False
            # 是否扫码
            itm['isScan'] = False
            # 扫码标识图标
            itm['icon'] = ''
            # 条码
            itm['bar_no'] = ''
            # 扫码数量
            itm['scanQty'] = 0
            itm['scanList'] = []
            itm['imageList'] = []
        msg = {'msg': '成功', "result": result}
        return make_response(jsonify(msg), 200)

# 进货送检转验收扫描条码匹配验收数量
class tfTiTiBarCodeView(Resource):
    @login_required
    def post(self):
        data = request.get_json()
        if data is None:
            return make_response(jsonify({'msg': '请提供参数'}), 202)
        # 0常规检验
        # 1复检
        type_ = data.get('type', 0)
        scan = data.get('scan', None)
        tiList = data.get('tiList', None)
        if scan is None or scan == '':
            return make_response(jsonify({'msg': '请提供单据类型常规/复检'}), 202)
        if scan is None or scan == '':
            return make_response(jsonify({'msg': '请扫条码'}), 202)
        if tiList is None:
            return make_response(jsonify({'msg': '请提供扫码数据类型参数'}), 202)

        if type(tiList) !=list:
            return make_response(jsonify({'msg': '扫码数据列表类型不对'}), 202)
        if len(tiList)==0:
            return make_response(jsonify({'msg': '扫码数据不能为空'}), 202)
        print(data)
        if len(tiList) == 0:
            return make_response(jsonify({'msg': '没有送检单，禁止扫码'}), 202)
        if len(tiList)==1:
            tilistStr = "c.ti_no+'/'+cast(c.itm as varchar(20)) ='{0}'".format(tiList[0])
        else:
            tilistStr = "c.ti_no+'/'+cast(c.itm as varchar(20)) in {0}".format(str(tuple(tiList)))
        print(tilistStr)
        if type_ == 0:
            print('常规检')
            sql_ = """
select c.PRD_MARK,c.wh,c1.dep as dep,c1.BIL_TYPE,c.ti_no+'/'+cast(c.itm as varchar(20)) as id,CASE WHEN a.scan_type='ser' then 1 else isnull(c.qty,0)-isnull(c.qty_rtn,0) end as qty, b.os_dd,c.ti_no,c.itm as ti_itm,a.* from (
select bar_no,prd_no,bat_no,bil_no,bil_itm,cus_no,'ser' as scan_type,prd_mark   from BAR_REC  where bil_id = 'PO'  and isnull(stop_id,'')!='T' and bar_no not in(select a1.BAR_CODE from tf_ty_b a1
left join tf_ty a2 on a1.ty_id=a2.ty_id and a1.itm=a2.itm and a1.ty_no=a2.ty_no 
where a1.TY_ID='TY' and isnull(a2.PRC_ID,'')!='4')
union all
select bar_code,prd_no,bat_no,bil_no,bil_itm,cus_no,'prd' as scan_type,prd_mark from PRDT_BARCODE WHERE bil_id = 'PO' ) a
left join tf_pos b on a.bil_itm=b.est_itm and a.bil_no=b.os_no 
left join tf_ti c on b.est_itm=c.est_itm and c.bil_no=b.os_no and c.ti_id='TI'
left join mf_ti c1 on c.ti_no=c1.ti_no and c.ti_id=c1.ti_id and c.ti_id='TI'
where isnull(c.ti_no,'')!='' and isnull(c.qty,0)-isnull(c.qty_rtn,0)>0 and {0} and a.bar_no=:scan and isnull(a.bat_no,'')=isnull(c.bat_no,'') and isnull(a.prd_mark,'')=isnull(c.prd_mark,'')
        """.format(tilistStr)
        else:
            print('复检')
            sql_ = """
select c.PRD_MARK,c.wh,c1.dep as dep,c1.BIL_TYPE, c.ti_no+'/'+cast(c.itm as varchar(20)) as id, case when a.scan_type='ser' then 1 else isnull(c.QTY_RCK,0) end as qty, b.os_dd,c.ti_no,c.itm as ti_itm,a.* from (
select bar_no,prd_no,bat_no,bil_no,bil_itm,cus_no,'ser' as scan_type,prd_mark  from BAR_REC  where bil_id = 'PO'  and isnull(stop_id,'')!='T' and bar_no not in(select a1.BAR_CODE from tf_ty_b a1
left join tf_ty a2 on a1.ty_id=a2.ty_id and a1.itm=a2.itm and a1.ty_no=a2.ty_no 
where a1.TY_ID='TY' and isnull(a2.PRC_ID,'')!='4')
union all
select bar_code,prd_no,bat_no,bil_no,bil_itm,cus_no,'prd' as scan_type,prd_mark  from PRDT_BARCODE WHERE bil_id = 'PO' ) a
left join tf_pos b on a.bil_itm=b.est_itm and a.bil_no=b.os_no 
left join tf_ti c on b.est_itm=c.est_itm and c.bil_no=b.os_no and c.ti_id='TI'
left join mf_ti c1 on c.ti_no=c1.ti_no and c.ti_id=c1.ti_id and c.ti_id='TI'
where isnull(c.ti_no,'')!='' and isnull(c.QTY_RCK,0)>0 and {0} and a.bar_no=:scan and isnull(a.bat_no,'')=isnull(c.bat_no,'') and isnull(a.prd_mark,'')=isnull(c.prd_mark,'')
        """.format(tilistStr)
        print(sql_)
        print(scan)
        result ,err= dbCurdD.dbListJon(sql_,{"scan":scan})
        if err !=None:
            print(err)
            return make_response(jsonify({'msg': '条码定位失败:'+err}), 202)

        if len(result) ==0:
            return make_response(jsonify({'msg': '条码已全部验收或不存在此单据中' + scan}), 202)
        countQty = 0
        for itm in result:
            countQty +=itm['qty']
        msg = {'msg': '成功', "result": result,'countQty':countQty}
        print(msg)
        return make_response(jsonify(msg), 200)

# 不合格原因
class spcListView(Resource):
    @login_required
    def get(self):
        sql_ = "select spc_no as id, name as label from SPC_LST"
        result, err = dbCurdD.dbListJon(sql_, {})
        if err!=None:
            return make_response(jsonify({'msg': '查询失败:' + err}), 202)
        msg = {'msg': '成功', "result": result}
        return make_response(jsonify(msg), 200)

class tyCurdListView(Resource):

    @login_required
    def get(self):
        data =  request.args
        page = int(data.get('page',1))
        str_date = data.get('str_date',None)
        ty_no = data.get('ty_no',None)
        est_date = data.get('est_date',None)
        cus_name = data.get('cus_name',None)
        pageSize = 50
        if str_date=='' or str_date is None:
            return make_response(jsonify({'msg': '开始日期不能为空'}), 202)
        if est_date=='' or est_date is None:
            return make_response(jsonify({'msg': '结束日期不能为空'}), 202)
        if data is None:
            return make_response(jsonify({'msg': '请提供查询参数'}), 202)

        parameter = "and a.ty_dd>=:str_date and a.ty_dd<=:est_date"
        parameter_d = {}
        parameter_d['page'] = page
        parameter_d['str_date'] = str_date
        parameter_d['est_date'] = est_date
        parameter_d['pageSize'] = pageSize
        # time.sleep(0.5)
        if cus_name !=None and cus_name!='':
            parameter +=" and b.name like :cus_name"
            parameter_d['cus_name'] = "%" + cus_name + "%"
        if ty_no !=None and ty_no!='':
            parameter +=" and a.ty_no like :ty_no"
            parameter_d['ty_no'] = "%" + ty_no + "%"
        # 查询总记录数
        count_sql = """
select count(*) as total from mf_ty a
left join cust b on a.cus_no=b.cus_no
where a.ty_id='TY' and isnull(scan_usr,'')!='' and left(ty_no,3)='TYS' {0}
        """.format(parameter)

    #     count_sql = """
    # select count(*) as total from mf_ty a
    # left join cust b on a.cus_no=b.cus_no
    # where a.ty_id='TY' {0}
    #             """.format(parameter)
        count_d, err = dbCurdD.dbOneJson(count_sql, parameter_d)
        print(count_sql)
        if err != None:
            print(err,'111')
            return make_response(jsonify({'msg': '统计查询失败:' + err}), 202)
        if count_d['total'] == 0:
            return make_response(jsonify({'msg': '没有查询到数据'}), 202)
        # 查询明细数据
        list_sql = """
select top (:pageSize) * 
from (select row_number() 
over(order by a.ty_dd desc) as rownumber, convert(nvarchar(80),a.ty_dd,23) as ty_dd,a.ty_no,a.cus_no,b.name as cus_name from mf_ty a
left join cust b on a.cus_no=b.cus_no
where a.ty_id='TY' and isnull(scan_usr,'')!='' and left(ty_no,3)='TYS' {0}) temp_row
where rownumber>((:page - 1) * :pageSize)
        """.format(parameter)

    #     list_sql = """
    # select top (:pageSize) *
    # from (select row_number()
    # over(order by a.ty_dd desc) as rownumber, convert(nvarchar(80),a.ty_dd,23) as ty_dd,a.ty_no,a.cus_no,b.name as cus_name from mf_ty a
    # left join cust b on a.cus_no=b.cus_no
    # where a.ty_id='TY' {0}) temp_row
    # where rownumber>((:page - 1) * :pageSize)
    #             """.format(parameter)
        list_d, err = dbCurdD.dbListJon(list_sql, parameter_d)
        if err!=None:
            print(err)
            return make_response(jsonify({'msg': '明细查询失败:' + err}), 202)

        # 计算总分页

        totalPage = math.ceil(count_d['total']/pageSize)
        print(222)
        print(count_d['total'])
        print(totalPage)
        previousPage = False if page<=1 else True
        nextPage = False if page>=totalPage else True
        result = {
            # 分页大小
            'pageSize':pageSize,
            # 是否有上一页
            'previousPage':previousPage,
            # 是否有下一页
            'nextPage':nextPage,
            # 总分页
            'totalPage':totalPage,
            'data':list_d,
            'page':page
        }
        print(result)
        msg = {'msg': '成功', "result": result}
        return make_response(jsonify(msg), 200)

    @login_required
    def post(self):
        """
        1、插入送检单单表头（MF_TY）
        TY_ID：单据别固定值(TY)        TY_ID：验收单号      TY_DD：验收日期      SAL_NO：验收人
        CUS_NO：供应商代号             TI_NO：来源送检单号   TB_NO：转出单号(NULL)    REM:来源单备注
        USR：制单人                    CHK_MAN：审核人      PRT_SW：打印标识(N)      CPY_SW---(NULL)
        BIL_NO:来源采购单            BIL_NO:来源采购单ID(PO)  CLS_DATE:审核日期       OLEFIELD：连接文档(NULL)
        BIL_TYPE:单据类别            DEP：单据部门           CUS_OS_NO：厂商订单号     MOB_ID：审核模板(NULL)
        LOCK_MAN:锁单人(NULL)       SYS_DATE:制单时间      CLS_ID_OK：结案合格量(NULL)     CLS_ID_LOST结案不合格量(NULL)
        PRT_USR:打印人员(NULL)      CHK_KND:检验类型        CANCEL_ID:作废标记(NULL)        MODIFY_DD:最近修改日期
        SCAN_USR：扫描人            SCAN_DATE:扫描日期      WMS_ID:WMS产生的单据(T)

        2、插入送检单表身（TF_TY）
        TY_ID:单据别(TY)       TY_NO:单据号码      ITM:单据项次    PRD_NO:单据编码     PRD_NAME:货品名称
        PRD_MARK:特征          WH:仓库              UNIT:单位(1)  QTY_CHK:验收数量    QTY_OK:验收合格量
        QTY1_OK:验收合格量副(NULL)    QTY_LOST:不合格量   REM:备注  BIL_NO:来源采购单号   TI_NO:送检单号
        BAT_NO:批号       SPC_NO:不合格原因代号         PRC_ID：不合格处理检验   EST_ITM：追踪已交数量项次
        PRE_ITM：原验收单项次  QTY1_CHK:验收数量副(NULL)      QTY1_LOST:不合格数量副(NULL)    FREE_ID:搭赠标识('')
        VALID_DD:有效期(NULL)    TI_ITM送检单项次       CAS_NO:工程案号     TASK_ID：阶段编号(NULL)
        CUS_OS_NO:(NULL)        CUS_OS_NO:客户订单号     DEP_RK:集团公司(NULL)   LS_NO:不合格审理单号(SL_NO)
        SL_NO:收料单号(NULL)    QC_UP:折价(NULL)         PRODU_DD:生产日期(NULL)      SH_NO_CUS:送货单号

        3、插入产品条码(PDA_BAR_COLLECT)一个记录如果有合格跟不合格的需要拆分成两笔记录
        BIL_ID:单据别(TY)  BIL_NO:单据号码     BIL_ITM:(0)     ITM扫码项次
        BAR_TYPE:(2)    BAR_CODE:条码     QTY_SCAN:扫码数量       QTY_PRD:PDA数量
        WH1：仓库      CHUW1:NULL      WH2:NULL        CHUW2:NULL
        SCAN_TIME:扫码时间      CONTAIN_CODE:(NULL)     QTY_ORIG:NULL   BIL_DD:来源单日期
        CUS_NO：供应商      DEP：部门      SYS_DATE：单据日期       USR：操作人
        BIL_TYPE:单据类别   SAL_NO:检验人
        4、插入条码序列号(TF_TY_B)
        TY_ID:(TY)      TY_NO:验收单号  TY_ITM:验收单项次   PRC_ID:不合格处理检验     ITM:扫描项次    PRD_MARK:特征     BAR_CODE：条码
        BOX_NO:批号       BIL_FLAG:(NULL)     REM('')     BOX_NO1:(NULL)

        5、修改送检单数据
        MF_TI:如果全部验收则更新结案标识CLOSE_ID(T)
        TF_TI:验收量QTY_RTN，如果不合格处理检验为复检则QTY_RTN

        6、修改采购单数据
        TF_POS:QTY_YS累积验收量  RK_CLS_ID:出入库结案标识

        7、修改验收单数据

        8、附件上传BIL_FILE
        附件id FILE_ID	附件类别BIL_ID(TY)	附件归属单号：BIL_NO	附件项次：BIL_ITM	附件名称FILE_NAME--001.png
        附件后缀：FILE_TYPE-.PNG	附件16进制：CONTENTf OX+'16进制'	附件上传日期：WRITE_DD	上传人：USR_WRITE
        THUMBNAIL(NULL)	FILE_SIZE(NULL)		FILE_NO(NULL)		CHK_TRANS(NULL)		TYPE_ID(NULL)		EST_ITM(NULL)
        select itm,est_itm,pre_itm,ti_itm,ty_no from tf_ty where ty_no='TY3626001'
union all
select itm,est_itm,pre_itm,'' as ti_itm,ti_no from tf_ti where ti_no='TI3626001' and prd_no='01.01.000013'
UNIon all
select itm,est_itm,pre_itm,'' as ti_itm,os_no from tf_pos where os_no='POJS36260001' and prd_no='01.01.000013'



delete from tf_ty where ty_no='TYS20230627001'
delete from BIL_FILE where bil_no='TYS20230627001'
delete from mf_ty where ty_no='TYS20230627001'
delete from pda_bar_collect where bil_no='TYS20230627001'
update tf_ti set QTY_RTN=0 where ti_no='TI3612005' and itm=1
update tf_ti set QTY_RTN=0 where ti_no='TI3612004' and itm=2
        :return:
        """
        data = request.get_json()

        dataList = data.get('dataList',None)
        scanType = data.get('scanType',None)  #0 常规检  1复检
        if scanType is None or scanType == '':
            return make_response(jsonify({'msg': '请提供扫码参数'}), 202)
        if dataList is None or dataList=='':
            return make_response(jsonify({'msg': '请提供数据参数' }), 202)
        if type(dataList)!=list:
            return make_response(jsonify({'msg': '数据类型不对'}), 202)
        if len(dataList)==0:
            return make_response(jsonify({'msg': '数据不能为空'}), 202)
        # 判断供应商单据类别部门是否一致
        tiList =[]
        cusDepTYPE = ''
        print(dataList)
        for itm in dataList:
            tiList.append(itm['ti_no'])
            print(itm)
            if len(itm['imageList'])>0:

                aaa = itm['imageList'][0]
                print(aaa)
                head, context = aaa.split(",")  # 将base64_str以“,”分割为两部分
                img_data = base64.b64decode(context)  # 解码时只要内容部分
                print(img_data)
                # image = Image.open(BytesIO(img_data))
                # print(image.filename)
                s = ''.join([hex(x)[2:].zfill(2) for x in img_data])

            # 判断来源单供应商、部门、单据类别是否一样
            if cusDepTYPE=='':
                cusDepTYPE = itm['cus_no'] + itm['dep'] + itm['bil_type']
            else:
                if cusDepTYPE !=itm['cus_no'] + itm['dep'] + itm['bil_type']:
                    return make_response(jsonify({'msg': '供应商、部门、单据类别不一致'}), 202)
        # 生成验收单号
        ty_no_sql = "select max(ty_no) as ty_no from MF_TY where ty_id='TY' AND convert(nvarchar(10),ty_dd,120) = convert(nvarchar(10),getdate(),120) and left(ty_no,3) ='TYS'"
        # ty_no_sql = "select max(ty_no) as ty_no from MF_TY where ty_id='TY' AND convert(nvarchar(10),ty_dd,120) = '2023-06-25' and left(ty_no,3) ='TYS'"
        ty_no_d ,err= dbCurdD.dbOneJson(ty_no_sql,{})
        if err!=None:
            return make_response(jsonify({'msg': '生成单号查询异常'+err}), 202)
        if ty_no_d['ty_no']==None:
            print('自动生成单号')
            ty_no = 'TYS' + datetime.datetime.now().strftime('%Y%m%d') + "%03d" % 1
        else:
            print('增加单号')
            print(ty_no_d)
            ty_no = ty_no_d['ty_no'][0:-3]+ "%03d" % (int(ty_no_d['ty_no'][-3:])+1)

        # 1、插入验收单表头信息
        mf_ty_sql = """
insert into mf_ty(ty_id,ty_no,ty_dd,sal_no,cus_no,ti_no,tb_no,rem,usr,chk_man,prt_sw,cpy_sw,bil_no,bil_id,cls_date,olefield,bil_type,dep,cus_os_no,mob_id,
lock_man,sys_date,cls_id_ok,cls_id_lost,prt_usr,chk_knd,cancel_id,modify_dd,scan_usr,scan_date,wms_id)
values(:ty_id,:ty_no,:ty_dd,:sal_no,:cus_no,:ti_no,:tb_no,:rem,:usr,:chk_man,:prt_sw,:cpy_sw,:bil_no,:bil_id,:cls_date,:olefield,:bil_type,:dep,:cus_os_no,:mob_id,
:lock_man,:sys_date,:cls_id_ok,:cls_id_lost,:prt_usr,:chk_knd,:cancel_id,:modify_dd,:scan_usr,:scan_date,:wms_id)
        """
        mf_ty = {}
        mf_ty['ty_id'] = 'TY'
        mf_ty['ty_no'] = ty_no
        mf_ty['ty_dd'] = datetime.datetime.now().strftime('%Y-%m-%d 00:00:000')
        mf_ty['sal_no'] = g.user['id']
        mf_ty['cus_no'] = dataList[0]['cus_no']
        mf_ty['ti_no'] = dataList[0]['ti_no']
        mf_ty['tb_no'] = None
        mf_ty['rem'] = None
        mf_ty['usr'] = g.user['id']
        mf_ty['chk_man'] = g.user['id']
        mf_ty['prt_sw'] = 'N'
        mf_ty['cpy_sw'] = None
        mf_ty['bil_no'] = dataList[0]['bil_no']
        mf_ty['bil_id'] = 'PO'
        mf_ty['cls_date'] = datetime.datetime.now()
        mf_ty['olefield'] = None
        mf_ty['bil_type'] = dataList[0]['bil_type']
        mf_ty['dep'] = g.user['dep']
        mf_ty['cus_os_no'] = None
        mf_ty['mob_id'] = None
        mf_ty['lock_man'] = None
        mf_ty['sys_date'] = datetime.datetime.now()
        mf_ty['cls_id_ok'] = None
        mf_ty['cls_id_lost'] = None
        mf_ty['prt_usr'] = None
        mf_ty['chk_knd'] = 2 if scanType==1 else 1
        mf_ty['cancel_id'] = None
        mf_ty['modify_dd'] = None
        mf_ty['scan_usr'] = g.user['id']
        mf_ty['scan_date'] = datetime.datetime.now()
        mf_ty['wms_id'] = 'T'

        new_db = db
        _,err = dbTransactionCurd.dbCPD(new_db, mf_ty_sql, mf_ty)
        if err!=None:
            return make_response(jsonify({'msg': '验收单表头新增失败' + err}), 202)
        # 2、插入验收单表身信息
        tf_ty_sql = """
insert into tf_ty(ty_id,ty_no,itm,prd_no,prd_name,prd_mark,wh,unit,qty_chk,qty_ok,qty1_ok,qty_lost,rem,bil_no,ti_no,bat_no,spc_no,prc_id,est_itm,
pre_itm,qty1_chk,qty1_lost,free_id,valid_dd,ti_itm,cas_no,task_id,cus_os_no,dep_rk,ls_no,sl_no,qc_up,produ_dd,sh_no_cus)
values(:ty_id,:ty_no,:itm,:prd_no,:prd_name,:prd_mark,:wh,:unit,:qty_chk,:qty_ok,:qty1_ok,:qty_lost,:rem,:bil_no,:ti_no,:bat_no,:spc_no,:prc_id,:est_itm,
:pre_itm,:qty1_chk,:qty1_lost,:free_id,:valid_dd,:ti_itm,:cas_no,:task_id,:cus_os_no,:dep_rk,:ls_no,:sl_no,:qc_up,:produ_dd,:sh_no_cus)
        """
        row_index = 0
        for index,itm in enumerate(dataList):
            print(index,'--',itm)
            # 1、判断数量是否超出
            sql1 = """
select c1.ti_dd,a.scan_type,c.PRD_MARK,c.wh,c1.dep as dep,c1.BIL_TYPE,c.ti_no+'/'+cast(c.itm as varchar(20)) as id,case when :scanType=0 then cast(isnull(c.qty,0)-isnull(c.qty_rtn,0) as float) else cast(isnull(c.QTY_RCK,0) as float) end as qty, b.os_dd,c.ti_no,c.itm as ti_itm,a.* from 
(select bar_no as bar_code,prd_no,bat_no,bil_no,bil_itm,cus_no,'ser' as scan_type,prd_mark from BAR_REC  where bil_id = 'PO'  and isnull(stop_id,'')!='T'
union all
select bar_code,prd_no,bat_no,bil_no,bil_itm,cus_no,'prd' as scan_type,prd_mark from PRDT_BARCODE WHERE bil_id = 'PO' ) a
left join tf_pos b on a.bil_itm=b.est_itm and a.bil_no=b.os_no 
left join tf_ti c on b.est_itm=c.est_itm and c.bil_no=b.os_no and c.ti_id='TI'
left join mf_ti c1 on c.ti_no=c1.ti_no and c.ti_id=c1.ti_id and c.ti_id='TI'
where isnull(c.ti_no,'')!='' and c.ti_no+'/'+cast(c.itm as varchar(20))=:id and a.bar_code=:bar_no and a.bat_no=c.bat_no and a.prd_mark=c.prd_mark
            """

            for index2,itm2 in enumerate(itm['scanList']):
                row_index += 1
                itm2['qty_ok'] = round(float(itm2['qty_ok']),4)
                itm2['qty_lost'] = round(float(itm2['qty_lost']),4)
                z_qty = itm2['qty_ok'] +itm2['qty_lost']
                itm_data,err = dbTransactionCurd.dbOneJson(new_db,sql1,{'scanType':scanType,"id":itm['id'],"bar_no":itm2["bar_no"]})
                if err!=None:
                    return make_response(jsonify({'msg': '查询每项数据失败'+err}), 202)
                if itm_data is None:
                    return make_response(jsonify({'msg': '此项数据已被抢先操作请刷新数据' + itm['id']}), 202)

                # z_qty=5
                print(row_index,'--',z_qty, '--', itm_data['qty'])
                if z_qty>itm_data['qty']:
                    print(z_qty,'--',itm_data['qty'])
                    return make_response(jsonify({'msg': '此项验收数量超出' + itm['id']}), 202)

                # 2、校验是否选择异常原因和一次处理建议
                if itm2['qty_lost'] > 0:
                    # itm['spc_no']=''
                    if itm2['spc_no']=='':
                        return make_response(jsonify({'msg': '此项没有选择不合格原因' + itm['id']}), 202)
                    # itm['prc_id'] = ''
                    if itm2['prc_id']=='':
                        return make_response(jsonify({'msg': '此项没有选择处理建议' + itm['id']}), 202)
                tf_ty = {}
                tf_ty['ty_id'] = 'TY'
                tf_ty['ty_no'] = ty_no
                tf_ty['itm'] = row_index
                tf_ty['prd_no'] = itm['prd_no']
                tf_ty['prd_name'] = itm['prd_name']
                tf_ty['prd_mark'] = itm['prd_mark']
                tf_ty['wh'] = itm['wh']
                tf_ty['unit'] = 1
                tf_ty['qty_chk'] = z_qty
                tf_ty['qty_ok'] = itm2['qty_ok']
                tf_ty['qty1_ok'] = 0
                tf_ty['qty_lost'] = itm2['qty_lost']
                tf_ty['rem'] = itm2['rem']
                tf_ty['bil_no'] = itm['bil_no']
                tf_ty['ti_no'] = itm['ti_no']
                tf_ty['bat_no'] = itm['bat_no']
                tf_ty['spc_no'] = itm2['spc_no']
                tf_ty['prc_id'] = itm2['prc_id']
                if itm2['qty_lost'] ==0:
                    tf_ty['spc_no'] = ''
                    tf_ty['prc_id'] = ''
                tf_ty['est_itm'] = itm['est_itm']
                tf_ty['pre_itm'] = row_index
                tf_ty['ti_itm'] = itm_data['ti_itm']
                tf_ty['qty1_chk'] = 0
                tf_ty['qty1_lost'] = 0
                tf_ty['free_id'] = itm['free_id']
                tf_ty['valid_dd'] = None
                tf_ty['cas_no'] = itm['cas_no']
                tf_ty['task_id'] = None
                tf_ty['cus_os_no'] = itm['cus_os_no']
                tf_ty['dep_rk'] = None
                tf_ty['ls_no'] = None
                tf_ty['sl_no'] = None
                tf_ty['qc_up'] = None
                tf_ty['produ_dd'] = None
                tf_ty['sh_no_cus'] =  itm['sh_no_cus']
                # 3、插入验收单表身
                _, err = dbTransactionCurd.dbCPD(new_db, tf_ty_sql, tf_ty)
                if err != None:
                    return make_response(jsonify({'msg': '验收单表身新增失败' + err}), 202)
                # 4、插入产品条码itm_data['scan_type']反之序列号条码
                if itm_data['scan_type']=='prd':
                    pda_bar_collect_sql = """
        insert into pda_bar_collect(bil_id,bil_no,bil_itm,itm,bar_type,bar_code,qty_scan,qty_prd,wh1,chuw1,wh2,chuw2,scan_time,contain_code,qty_orig,bil_dd,cus_no,dep,sys_date,usr,bil_type,sal_no)
        values(:bil_id,:bil_no,:bil_itm,:itm,:bar_type,:bar_code,:qty_scan,:qty_prd,:wh1,:chuw1,:wh2,:chuw2,:scan_time,
        :contain_code,:qty_orig,:bil_dd,:cus_no,:dep,:sys_date,:usr,:bil_type,:sal_no)
                    """
                    pda_bar_collect = {}
                    pda_bar_collect['bil_id'] = 'TY'
                    pda_bar_collect['bil_no'] = ty_no
                    pda_bar_collect['bil_itm'] = 0
                    pda_bar_collect['itm'] = row_index
                    pda_bar_collect['bar_type'] = 2
                    pda_bar_collect['bar_code'] = itm2['bar_no']
                    pda_bar_collect['qty_scan'] = itm2['qty_ok']
                    pda_bar_collect['qty_prd'] = itm2['qty_ok']
                    pda_bar_collect['wh1'] = itm['wh']
                    pda_bar_collect['chuw1'] = None
                    pda_bar_collect['wh2'] = None
                    pda_bar_collect['chuw2'] = None
                    pda_bar_collect['scan_time'] = datetime.datetime.now()
                    pda_bar_collect['contain_code'] = None
                    pda_bar_collect['qty_orig'] = None
                    pda_bar_collect['bil_dd'] = itm_data['ti_dd']
                    pda_bar_collect['cus_no'] = itm_data['cus_no']
                    pda_bar_collect['dep'] = g.user['dep']
                    pda_bar_collect['sys_date'] = datetime.datetime.now()
                    pda_bar_collect['bil_type'] =itm['bil_type']
                    pda_bar_collect['usr'] = g.user['id']
                    pda_bar_collect['sal_no'] = g.user['id']
                    if itm2['qty_ok']>0:
                        _, err = dbTransactionCurd.dbCPD(new_db, pda_bar_collect_sql, pda_bar_collect)
                        if err != None:
                            return make_response(jsonify({'msg': '产品条码合格新增失败' + err}), 202)
                    if itm['qty_lost']>0:
                        pda_bar_collect['qty_scan'] = itm2['qty_lost']
                        pda_bar_collect['qty_prd'] = itm2['qty_lost']
                        pda_bar_collect['itm'] = -(row_index)
                        _, err = dbTransactionCurd.dbCPD(new_db, pda_bar_collect_sql, pda_bar_collect)
                        if err != None:
                            return make_response(jsonify({'msg': '产品条码不合格新增失败' + err}), 202)
                else:

                    if itm2['qty_ok']!=1 and itm2['qty_lost']!=1:
                        return make_response(jsonify({'msg': '此项次序列号条码数量应该是1' + itm['id']}), 202)
                    tf_ty_b_sql = """
    insert into tf_ty_b(ty_id,ty_no,ty_itm,prc_id,itm,prd_mark,bar_code,box_no,bil_flag,rem,box_no1)
    values(:ty_id,:ty_no,:ty_itm,:prc_id,:itm,:prd_mark,:bar_code,:box_no,:bil_flag,:rem,:box_no1)
                    """
                    tf_ty_b = {}
                    tf_ty_b['ty_id'] = 'TY'
                    tf_ty_b['ty_no'] = ty_no
                    tf_ty_b['ty_itm'] = row_index
                    tf_ty_b['itm'] = row_index
                    tf_ty_b['prd_mark'] = itm['prd_mark']
                    tf_ty_b['bar_code'] = itm2['bar_no']
                    tf_ty_b['box_no'] = None
                    tf_ty_b['bil_flag'] = None
                    tf_ty_b['rem'] = None
                    tf_ty_b['box_no1'] = None
                    tf_ty_b['prc_id'] = itm2['prc_id'] if itm2['qty_lost']==1 else ''
                    print(tf_ty_b)
                    _, err = dbTransactionCurd.dbCPD(new_db, tf_ty_b_sql, tf_ty_b)
                    if err != None:
                        return make_response(jsonify({'msg': '序列号条码新增失败' + err}), 202)
                # 5、上传附件
                if len(itm2['imageList'])>0:
                    for imgindex,imgitm in enumerate(itm2['imageList']):
                        # print(itm['imageList'][0])
                        # 将图片切割
                        imageSplit =  imgitm.split(';base64,', 1)
                        if len(imageSplit)!=2:
                            db.session.rollback()
                            db.session.close()
                            return make_response(jsonify({'msg': '此项图片上传异常' + itm['id']}), 202)
                        # print(imageSplit)
                        bil_file_sql = """
    insert into bil_file(file_id,bil_id,bil_no,bil_itm,file_name,file_type,content,write_dd,usr_write,file_no,chk_trans,type_id,est_itm)
    values(:file_id,:bil_id,:bil_no,:bil_itm,:file_name,:file_type,:content,:write_dd,:usr_write,:file_no,:chk_trans,:type_id,:est_itm)
    
                        """
                        try:
                            # contentOx = '0x' + base64.b64decode(imageSplit[1]).hex()
                            contentOx = base64.b64decode(imageSplit[1])
                        except:
                            db.session.rollback()
                            db.session.close()
                            return make_response(jsonify({'msg': '此项图片转换异常' + itm['id']}), 202)
                        bil_file = {}
                        bil_file['file_id'] = ty_no + str(imgindex) + str(datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')) + "%05d" % 0
                        bil_file['bil_id'] = 'TY'
                        bil_file['bil_no'] = ty_no
                        bil_file['bil_itm'] = row_index
                        bil_file['file_type'] = '.' + imageSplit[0][11:].upper()
                        bil_file['file_name'] = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')) +  str((imgindex+1 )) + '.' + imageSplit[0][11:]

                        bil_file['content'] = contentOx
                        bil_file['write_dd'] = datetime.datetime.now()
                        bil_file['usr_write'] = g.user['id']
                        # bil_file['thumbnail'] = None
                        # bil_file['file_size'] = None
                        bil_file['file_no'] = None
                        bil_file['chk_trans'] = None
                        bil_file['type_id'] = None
                        bil_file['est_itm'] = None
                        _, err = dbTransactionCurd.dbCPD(new_db, bil_file_sql, bil_file)
                        if err != None:
                            print(err)
                            return make_response(jsonify({'msg': '图片上传异常' + err}), 202)

                # 判断修改送检单是否结案以及修改送检单表身回写数量
                mf_ti_sql = """
    update tf_ti set qty_rtn = qty_rtn + :qty_rtn,qty_rck = qty_rck + :qty_rck where  ti_id='TI' and ti_no+'/'+cast(itm as varchar(20))=:id
    update mf_ti set close_id= case when (select sum(isnull(qty_rtn,0))-sum(isnull(qty_rck,0)) from tf_ti where ti_id='TI' and ti_no=:ti_no)>=
    (select sum(isnull(qty,0)) from tf_ti where ti_id='TI' and ti_no=:ti_no) then 'T' else 'F' end where ti_id='TI' and ti_no=:ti_no
                """
                mf_ti = {}

                # 复检单据
                if scanType==1:
                    print('修改复检')
                    mf_ti['qty_rtn'] = 0
                    if itm2['prc_id']=='4':
                        mf_ti['qty_rck'] = -itm2['qty_ok']
                    else:
                        mf_ti['qty_rck'] = -(itm2['qty_ok'] + itm2['qty_lost'])
                else:
                    print('修改常规检')
                    print('处理建议',itm2['prc_id'],'--',itm2['qty_lost'])
                    print(type(itm2['prc_id']))
                    mf_ti['qty_rtn'] = itm2['qty_ok'] + itm2['qty_lost']
                    if itm2['prc_id'] == '4':
                        mf_ti['qty_rck'] = itm2['qty_lost']
                    else:
                        mf_ti['qty_rck'] = 0
                mf_ti['id'] = itm['id']
                mf_ti['ti_no'] = itm['ti_no']
                mf_ti['scanType'] = scanType
                print(mf_ti)
                print(mf_ti_sql)
                _, err = dbTransactionCurd.dbCPD(new_db, mf_ti_sql, mf_ti)
                if err != None:
                    print(err)
                    return make_response(jsonify({'msg': '此项回写送检量失败' + itm['id']+err}), 202)

        new_db.session.commit()
        msg = {'msg': '成功'}
        return make_response(jsonify(msg), 201)


class tyCurdPkView(Resource):

    @login_required
    def get(self,pk):
        # time.sleep(0.5)
        # 查询表头
        mf_sql = """
select a.ty_no,convert(nvarchar(80),a.ty_dd,23) as ty_dd,a.cus_no,b.name as cus_name,a.sal_no,c.name as sal_name,d.dep,d.name as dep_name,a.rem,a.chk_knd from mf_ty a
left join cust b on a.cus_no=b.cus_no
left join salm c on a.sal_no=c.sal_no
left join dept d on a.dep=d.dep
where a.ty_no=:pk
        """
        # 查询表身
        tf_sql = """
select a.ty_no+'/'+cast(a.itm as varchar(20)) as id, a.itm,a.prd_no,b.name as prd_name,b.ut,isnull(a.qty_chk,0) as qty_chk,isnull(a.qty_ok,0) as qty_ok,isnull(a.qty_lost,0) as qty_lost,c.name as spc_name,case when a.prc_id='1' then '验收退回'
when a.prc_id='2' then '让步接收' when a.prc_id='4' then '复检' else '' end as prc_name
from tf_ty a
left join prdt b on a.prd_no=b.prd_no
left join spc_lst c on a.spc_no=c.spc_no
where a.ty_no=:pk
        """
        mar = {'pk':pk}
        mf_d,err = dbCurdD.dbOneJson(mf_sql,mar)
        if err !=None:
            return make_response(jsonify({'msg': '表头查询失败:' + err}), 202)
        if mf_d is None:
            return make_response(jsonify({'msg': '表头没有查询到数据'}), 202)
        tf_d, err = dbCurdD.dbListJon(tf_sql, mar)
        if err != None:
            return make_response(jsonify({'msg': '表头查询失败:' + err}), 202)

        result = {
            'mf':mf_d,
            'tf':tf_d
        }
        msg = {'msg': '成功', "result": result}
        return make_response(jsonify(msg), 200)

    @login_required
    def delete(self, pk):
        new_db = db
        pmar = {'pk':pk}
        print(pmar)
        # 判断单据是否存在
        mf_ty_s = """
select a.ty_no,a.chk_knd ,isnull(b.end_qty,0) as end_qty from mf_ty a
left join (select sum(isnull(QTY_OK_RTN ,0)+isnull(QTY_LOST_RTN,0)) as end_qty,ty_no from tf_ty group by ty_no)b on a.ty_no=b.ty_no
where a.ty_id='TY' and a.ty_no =:pk
        """
        mf_ty_s_d ,err = dbTransactionCurd.dbOneJson(new_db,mf_ty_s,pmar)
        print(mf_ty_s_d)
        print(mf_ty_s)
        if err != None:
            print(err)
            return make_response(jsonify({'msg': '验收单表头查询失败'+ err}), 202)
        if mf_ty_s is None:
            return make_response(jsonify({'msg': '单据不存在禁止删除'}), 202)
        if mf_ty_s_d['end_qty']!=0:
            return make_response(jsonify({'msg': '已转后续单据禁止删除'}), 202)
        # 1、表身删除送检单自定义表 tf_ty_z
        tf_ty_z_sql = "delete from tf_ty_z where ty_id='TY' and ty_no=:pk"
        _,err = dbTransactionCurd.dbCPD(new_db,tf_ty_z_sql,{'pk':pk})
        if err != None:
            print(err)
            return make_response(jsonify({'msg': '验收单表头删除失败'+ err}), 202)
        # 2、删除产品条码  PDA_BAR_COLLECT
        pda_bar_collect_sql = "delete from pda_bar_collect where bil_id='TY' and bil_no=:pk"
        _, err = dbTransactionCurd.dbCPD(new_db, pda_bar_collect_sql, pmar)
        if err != None:
            print(err)
            return make_response(jsonify({'msg': '验收单产品条码删除失败' + err}), 202)
        # 3、删除序列号条码   TF_TY_B
        tf_ty_b_sql = "delete from tf_ty_b where ty_id='TY' and ty_no=:pk"
        _, err = dbTransactionCurd.dbCPD(new_db, tf_ty_b_sql, pmar)
        if err != None:
            print(err)
            return make_response(jsonify({'msg': '验收单序列号条码删除失败' + err}), 202)
        # 4、删除附件    BIL_FILE
        bil_file_sql = "delete from bil_file where bil_id='TY' and bil_no=:pk"
        _, err = dbTransactionCurd.dbCPD(new_db, tf_ty_b_sql,pmar)
        if err != None:
            print(err)
            return make_response(jsonify({'msg': '验收单附件删除失败' + err}), 202)
        # 5、查询表身数据
        print(pk)
        tf_ty_s = "select ti_no,ti_itm,qty_ok,qty_lost,prc_id from tf_ty where ty_id='TY' and ty_no=:pk"
        tf_ty_s_d,err = dbTransactionCurd.dbListJon(new_db,tf_ty_s,pmar)
        if err != None:
            print(err)
            return make_response(jsonify({'msg': '验收单表身查询失败' + err}), 202)
        print(tf_ty_s_d)
        for itm in tf_ty_s_d:
            print(itm)
            print('88888',itm)
            if mf_ty_s_d['chk_knd']=='1':
                # 常规验收单
                print('进入的是常规检验1')
                qty_rtn = itm['qty_lost'] + itm['qty_ok']
                qty_rck = 0
                if itm['qty_lost'] > 0 and itm['prc_id'] == '4':
                    print('进入了不合格复检')
                    qty_rck = itm['qty_lost'] #回写复检数量 -
            else:
                # 复检单据
                print('进入的是复检1')
                qty_rtn = 0
                if itm['qty_lost']>0 and itm['prc_id']=='4':
                    # 当处理建议为复检的时候
                    qty_rck = -itm['qty_ok']  # 回写复检数量 +
                else:
                    qty_rck = -(itm['qty_lost'] + itm['qty_ok'])
            tf_ti_sql = "update tf_ti set qty_rck=isnull(qty_rck,0) - (:qty_rck),qty_rtn = isnull(qty_rtn,0) - (:qty_rtn) where itm=:ti_itm and ti_no=:ti_no and ti_id='TI'"
            tf_ti_sql_m = {}
            tf_ti_sql_m['qty_rtn'] = qty_rtn
            tf_ti_sql_m['qty_rck'] = qty_rck
            tf_ti_sql_m['ti_itm'] = itm['ti_itm']
            tf_ti_sql_m['ti_no'] = itm['ti_no']
            print(tf_ti_sql_m)
            print(tf_ti_sql)
            # 6、修改送检单表身回写
            _,err = dbTransactionCurd.dbCPD(new_db,tf_ti_sql,tf_ti_sql_m)
            if err != None:
                print(err)
                return make_response(jsonify({'msg': '验收单删除回写送检单表身失败' + err}), 202)
            # 7、修改送检单表头结案标识
            mf_ti_sql = "update mf_ti set close_id='F' where ti_id='TI' and ti_no=:ti_no"
            _, err = dbTransactionCurd.dbCPD(new_db, mf_ti_sql, tf_ti_sql_m)
            if err != None:
                print(err)
                return make_response(jsonify({'msg': '验收单删除回写送检单表身失败' + err}), 202)
        # 8、删除表身  tf_ty
        tf_ty_sql = "delete from tf_ty where ty_id='TY' and ty_no=:pk"
        _, err = dbTransactionCurd.dbCPD(new_db, tf_ty_sql, pmar)
        if err != None:
            print(err)
            return make_response(jsonify({'msg': '验收单表身删除失败' + err}), 202)
        # 9、删除表头    mf_ty
        mf_ty_sql = "delete from mf_ty where ty_id='TY' and ty_no=:pk"
        _, err = dbTransactionCurd.dbCPD(new_db, mf_ty_sql, pmar)
        if err != None:
            print(err)
            return make_response(jsonify({'msg': '验收单表头删除失败' + err}), 202)
        new_db.session.commit()
        msg = {'msg': '成功'}
        return make_response(jsonify(msg), 204)
